<template>
  <ClientOnly>
    <UPage>
      <UPageBody class="flex items-center justify-center">
        <UCard class="w-full max-w-sm">
          <UAuthForm
            :title="isLogin ? '登录' : '注册'"
            :description="isLogin ? '欢迎回来！' : '创建一个新账户'"
            :fields="fields"
            :schema="schema"
            :providers="providers"
            :submit="{
              label: isLogin ? '登录' : '注册',
              variant: 'subtle'
            }"
            @submit="handleSubmit"
          >
            <template #footer>
              <UButton
                variant="link"
                @click="toggleMode"
              >
                {{ isLogin ? "还没有账户？去注册" : "已有账户？去登录" }}
              </UButton>
            </template>
          </UAuthForm>
        </UCard>
      </UPageBody>
    </UPage>
    <UButton
      variant="link"
      @click="loginGotee"
    >
      Gitee
    </UButton>
  </ClientOnly>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { z } from 'zod'
import type { FormSubmitEvent } from '#ui/types'

const isLogin = ref(true)

const schema = z.object({
//   email: z.email('无效的邮箱地址').min(3, '邮箱最少需要3位'),
  email: z.string('无效的邮箱地址').min(3, '邮箱最少需要3位'),
  password: z.string('密码不能为空').min(3, '密码最少需要3位')
})

type Schema = z.infer<typeof schema>

const fields = ref([
  {
    name: 'email',
    type: 'text' as const,
    label: '邮箱',
    placeholder: '请输入您的邮箱'
  },
  {
    name: 'password',
    type: 'password' as const,
    label: '密码',
    placeholder: '请输入您的密码'
  }
])

const providers = ref([
  {
    label: '通过 GitHub 登录',
    icon: 'i-simple-icons-github',
    color: 'secondary' as const,
    click: () => handleSocialLogin('github')
  },
  {
    label: '通过 Gitee 登录',
    icon: 'i-simple-icons-gitee',
    color: 'secondary' as const,
    click: () => handleSocialLogin('gitee')
  }
])

const loginGotee = async () => {
  await authClient.signIn.oauth2({
    providerId: 'li-gitee',
    callbackURL: '/',
    scopes: ['user_info']
  })
}

const toggleMode = () => {
  isLogin.value = !isLogin.value
}

const toast = useToast()
const handleLogin = async (data: Schema) => {
  try {
    console.log('执行登录逻辑', data)

    const { data: resp, error } = await authClient.signIn.email({
      email: data.email,
      password: data.password,
      callbackURL: '/profile'
    }, {
      onRequest: (ctx) => {
        // 显示加载状态
        console.log('onRequest', ctx)
      },
      onSuccess: (ctx) => {
        // 登录成功，重定向到个人资料页面
        console.log('onSuccess', ctx)
        toast.add({
          title: '登录成功',
          description: `欢迎回来，${ctx.data.user?.name || data.email}`,
          color: 'success'
        })
      },
      onError: (ctx) => {
        // 显示错误信息
        console.log('onError', ctx)
        toast.add({
          title: '登录失败',
          description: ctx.error.message || ctx.error.statusText || '请检查您的邮箱和密码',
          color: 'error'
        })
      }
    })

    console.log(resp, error)
  } catch (err) {
    console.error('登录过程中发生错误:', err)
    toast.add({
      title: '登录失败',
      description: '登录过程中发生错误，请稍后再试',
      color: 'error'
    })
  }
}

const handleRegister = async (data: Schema) => {
  console.log('执行注册逻辑', data)
  const { data: resp, error } = await authClient.signUp.email({
    email: data.email,
    password: data.email,
    name: data.email.substring(0, data.email.indexOf('@')),
    callbackURL: '/profile'
  }, {
    onRequest: (ctx) => {
      // show loading

      console.log('onRequest', ctx)
    },
    onSuccess: (ctx) => {
      // redirect to the dashboard or sign in page

      console.log('onSuccess', ctx)
    },
    onError: (ctx) => {
      // display the error message
      console.log('onError', ctx)
      alert(ctx.error.message)
      toast.add({
        title: '注册失败',
        description: ctx.error.message || ctx.error.statusText,
        color: 'error'
      })
    }
  })
  console.log(resp, error)
}

const handleSubmit = (event: FormSubmitEvent<Schema>) => {
  if (isLogin.value) {
    handleLogin(event.data)
  } else {
    handleRegister(event.data)
  }
}

const handleSocialLogin = async (provider: 'github' | 'gitee') => {
  try {
    console.log(`通过 ${provider} 登录`)
    await authClient.signIn.oauth2({
      providerId: provider === 'github' ? 'github' : 'li-gitee',
      callbackURL: '/'
    })
  } catch (error) {
    console.error(`${provider} 登录失败:`, error)
    toast.add({
      title: '登录失败',
      description: `${provider} 登录过程中发生错误，请稍后再试`,
      color: 'error'
    })
  }
}
</script>
